⚙️ c12
c12 (pronounced as /siːtwelv/, like c-twelve) is a smart configuration loader.
✅ Features
🦴 Used by
Usage
Install package:
npx nypm install c12
npm install c12
yarn add c12
pnpm install c12
bun install c12
deno install c12
Import:
ESM (Node.js, Bun, Deno)
import { loadConfig, watchConfig } from "c12";
CommonJS (Legacy Node.js)
const { loadConfig, watchConfig } = require("c12");
Load configuration:
const { config } = await loadConfig({});
const { config, configFile, layers } = await loadConfig({});
Loading priority
c12 merged config sources with unjs/defu by below order:
- Config overrides passed by options
- Config file in CWD
- RC file in CWD
- Global RC file in the user's home directory
- Config from
package.json
- Default config passed by options
- Extended config layers
Options
cwd
Resolve configuration from this working directory. The default is process.cwd()
name
Configuration base name. The default is config
.
configFile
Configuration file name without extension. Default is generated from name
(f.e., if name
is foo
, the config file will be => foo.config
).
Set to false
to avoid loading the config file.
rcFile
RC Config file name. Default is generated from name
(name=foo => .foorc
).
Set to false
to disable loading RC config.
globalRC
Load RC config from the workspace directory and the user's home directory. Only enabled when rcFile
is provided. Set to false
to disable this functionality.
dotenv
Loads .env
file if enabled. It is disabled by default.
packageJson
Loads config from nearest package.json
file. It is disabled by default.
If true
value is passed, c12 uses name
field from package.json
.
You can also pass either a string or an array of strings as a value to use those fields.
defaults
Specify default configuration. It has the lowest priority and is applied after extending config.
defaultConfig
Specify default configuration. It is applied before extending config.
overrides
Specify override configuration. It has the highest priority and is applied before extending config.
omit$Keys
Exclude environment-specific and built-in keys start with $
in the resolved config. The default is false
.
jiti
Custom unjs/jiti instance used to import configuration files.
jitiOptions
Custom unjs/jiti options to import configuration files.
giget
Options passed to unjs/giget when extending layer from git source.
merger
Custom options merger function. Default is defu.
Note: Custom merge function should deeply merge options with arguments high -> low priority.
envName
Environment name used for environment specific configuration.
The default is process.env.NODE_ENV
. You can set envName
to false
or an empty string to disable the feature.
Extending configuration
If resolved config contains a extends
key, it will be used to extend the configuration.
Extending can be nested and each layer can extend from one base or more.
The final config is merged result of extended options and user options with unjs/defu.
Each item in extends is a string that can be either an absolute or relative path to the current config file pointing to a config file for extending or the directory containing the config file.
If it starts with either github:
, gitlab:
, bitbucket:
, or https:
, c12 automatically clones it.
For custom merging strategies, you can directly access each layer with layers
property.
Example:
export default {
colors: {
primary: "user_primary",
},
extends: ["./theme"],
};
export default {
dev: true,
};
export default {
extends: "../base",
colors: {
primary: "theme_primary",
secondary: "theme_secondary",
},
};
export default {
colors: {
primary: "base_primary",
text: "base_text",
},
};
The loaded configuration would look like this:
const config = {
dev: true,
colors: {
primary: "user_primary",
secondary: "theme_secondary",
text: "base_text",
},
};
Layers:
[
{
config: {
},
configFile: "/path/to/theme/config.ts",
cwd: "/path/to/theme ",
},
{
config: {
},
configFile: "/path/to/base/config.ts",
cwd: "/path/to/base",
},
{
config: {
},
configFile: "/path/to/config.dev.ts",
cwd: "/path/",
},
];
Extending config layer from remote sources
You can also extend configuration from remote sources such as npm or github.
In the repo, there should be a config.ts
(or config.{name}.ts
) file to be considered as a valid config layer.
Example: Extend from a github repository
export default {
extends: "gh:user/repo",
};
Example: Extend from a github repository with branch and subpath
export default {
extends: "gh:user/repo/theme#dev",
};
Example: Extend a private repository and install dependencies:
export default {
extends: ["gh:user/repo", { auth: process.env.GITHUB_TOKEN, install: true }],
};
You can pass more options to giget: {}
in layer config or disable it by setting it to false
.
Refer to unjs/giget for more information.
Environment-specific configuration
Users can define environment-specific configuration using these config keys:
$test: {...}
$development: {...}
$production: {...}
$env: { [env]: {...} }
c12 tries to match envName
and override environment config if specified.
Note: Environment will be applied when extending each configuration layer. This way layers can provide environment-specific configuration.
Example:
export default {
logLevel: "info",
$test: { logLevel: "silent" },
$development: { logLevel: "warning" },
$production: { logLevel: "error" },
$env: {
staging: { logLevel: "debug" },
},
};
Watching configuration
you can use watchConfig
instead of loadConfig
to load config and watch for changes, add and removals in all expected configuration paths and auto reload with new config.
Lifecycle hooks
onWatch
: This function is always called when config is updated, added, or removed before attempting to reload the config.acceptHMR
: By implementing this function, you can compare old and new functions and return true
if a full reload is not needed.onUpdate
: This function is always called after the new config is updated. If acceptHMR
returns true, it will be skipped.
import { watchConfig } from "c12";
const config = watchConfig({
cwd: ".",
onWatch: (event) => {
console.log("[watcher]", event.type, event.path);
},
acceptHMR({ oldConfig, newConfig, getDiff }) {
const diff = getDiff();
if (diff.length === 0) {
console.log("No config changed detected!");
return true;
}
},
onUpdate({ oldConfig, newConfig, getDiff }) {
const diff = getDiff();
console.log("Config updated:\n" + diff.map((i) => i.toJSON()).join("\n"));
},
});
console.log("watching config files:", config.watchingFiles);
console.log("initial config", config.config);
Updating config
[!NOTE]
This feature is experimental
Update or create a new configuration files.
Add magicast
peer dependency:
npx nypm install -D magicast
npm install -D magicast
yarn add -D magicast
pnpm install -D magicast
bun install -D magicast
deno install --dev magicast
Import util from c12/update
const { configFile, created } = await updateConfig({
cwd: ".",
configFile: "foo.config",
onCreate: ({ configFile }) => {
console.log(`Creating new config file in ${configFile}...`);
return "export default { test: true }";
},
onUpdate: (config) => {
config.test2 = false;
},
});
console.log(`Config file ${created ? "created" : "updated"} in ${configFile}`);
Contribution
Local development
- Clone this repository
- Install the latest LTS version of Node.js
- Enable Corepack using
corepack enable
- Install dependencies using
pnpm install
- Run tests using
pnpm dev
or pnpm test
License
Published under the MIT license.
Made by @pi0 and community 💛
🤖 auto updated with automd